package com.douqu.game.auth.web.controller;

import com.alibaba.fastjson.JSONObject;
import com.bean.core.util.HttpJsonUtils;
import com.bean.core.util.MD5Utils;
import com.bean.core.util.TimeUtils;
import com.douqu.game.auth.database.mapper.ServerMapper;
import com.douqu.game.auth.database.model.ServerModel;
import com.douqu.game.auth.service.OrderRecordService;
import com.douqu.game.auth.service.PlayerService;
import com.douqu.game.auth.web.request.YjCheckOrderReqParam;
import com.douqu.game.core.factory.ConstantFactory;
import com.douqu.game.core.factory.HttpFactory;
import com.douqu.game.core.protobuf.SGCommonProto;
import com.douqu.game.core.util.LogUtils;
import com.douqu.game.core.util.PayUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
* @author wangzhenfei
*         2018-01-17 15:42
*         易接消费回调
*/
@RestController
public class YjNotifyController {

    @Autowired
    PlayerService playerService;

    @Autowired
    ServerMapper serverMapper;

    @Autowired
    OrderRecordService orderRecordService;

    @RequestMapping(value = "/yj/test")
    public void test(HttpServletRequest request, HttpServletResponse response) throws IOException {
        PrintWriter w = response.getWriter();
        LogUtils.error("收到测试数据");
        w.write("hahahahahaha");
        w.flush();
        w.close();
    }


    @RequestMapping(value = "/yj/checkOrder")
    public void checkOrder(HttpServletRequest request, HttpServletResponse response) throws IOException {
        PrintWriter w = response.getWriter();
        YjCheckOrderReqParam orderReqDto = new YjCheckOrderReqParam();
        orderReqDto.init(request);
        LogUtils.info("回调参数：" + orderReqDto.toString());
        if(orderReqDto.isResultOk()){
            // 此处CP可以持久化消费记录
            //st==1是支付成功，才能给用户发道具
            if(orderReqDto.isSuccess()){
                Integer count = orderRecordService.findCount(orderReqDto.getInnerParam().getObjectIndex(), orderReqDto.getTcd());
                if(count == null || count == 0){ //没有成功的记录，发送奖励
                    //TODO 发送奖励
                    //获取服务器id
                    Integer serverId = orderReqDto.getInnerParam().getServerId();
                    ServerModel serverModel = serverMapper.selectByPrimaryKey(serverId);
                    if(serverModel == null){
                        LogUtils.error("服务器找不到 id为:" + serverId);
                        w.write("ERROR");
                    }else{
                        String checkString = orderReqDto.getInnerParam().getServerId() + ConstantFactory.RECHARGE_KEY +
                                TimeUtils.getCurrentTime(TimeUtils.YYYYMMDD);
                        JSONObject jsonObject = new JSONObject();
                        jsonObject.put("objectIndex", orderReqDto.getInnerParam().getObjectIndex());
                        jsonObject.put("rechargeParam", orderReqDto.getCbi());
                        jsonObject.put("tcd", orderReqDto.getTcd());
                        jsonObject.put("fee", orderReqDto.getFee());
                        jsonObject.put("channel", orderReqDto.getSdk());

                        String payType = PayUtils.getEnumType(SGCommonProto.E_RECHARGE_TYPE.RECHARGE_TYPE_YJ.name());
                        jsonObject.put("payType", payType);
                        jsonObject.put("password", MD5Utils.encodeUppercase(checkString));
                        LogUtils.info("带验证充值密码字符串:" + checkString);

                        LogUtils.info("参数  -> " + jsonObject.toJSONString());

                        LogUtils.info("通知主服务器 -> "+ serverModel.getMainServerRequestUrl());
                        JSONObject result = HttpJsonUtils.httpPost(serverModel.getMainServerRequestUrl() + HttpFactory.ORDER_CHECK, jsonObject);
                        if(result != null){
                            String resultCode = result.getString("code");
                            if(Integer.parseInt(resultCode) == 0){//成功
                                orderRecordService.updateOrder(orderReqDto.getOrderRecordModel(payType), true);
                                LogUtils.info("充值成功 -> ");
                                w.write("SUCCESS");
                                //充值成功调用talkingData

                            }else {
                                LogUtils.error("主服务器返回充值错误：" + result.getString("message"));
                                w.write("ERROR");
                            }
                        }else {
                            LogUtils.error("主服务器返回充值错误返回为空");
                            w.write("ERROR");
                        }
                    }

                }else {
                    LogUtils.error("该用户已经发放过奖励");
                    w.write("SUCCESS");
                }
            }
            // 操作成功后需要返回SUCCESS告诉易接服务器已经接收成功

        }else{
            // 返回ERROR易接服务器会根据一定的策略重新同步消费记录给CP
            LogUtils.error("ERROR");
            w.write("ERROR");
        }
        w.flush();
        w.close();
    }


    
}
